package online.afeibaili.storebackendframework.server;

import online.afeibaili.storebackendframework.af.OrderInterface;
import online.afeibaili.storebackendframework.mapper.ProductMapper;
import online.afeibaili.storebackendframework.model.Product;
import online.afeibaili.storebackendframework.other.OrderInterfaceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class StatServer {
    @Autowired
    private ProductServer productServer;
    
    @Autowired
    private OrderInterface orderInterface;

    public List<Map<String, Object>> selectStat(long startTime, long endTime) {
        Date date = new Date();
        List<Object> productStat = orderInterface.selectStat(startTime, endTime);
        Date date1 = new Date();
        System.out.println(date1.getTime() - date.getTime()+"msAF");
        List<Map<String, Object>> stats = new ArrayList<>();
        
        // 收集所有需要查询的产品createTime
        List<Long> createTimes = new ArrayList<>();
        for (Object o : productStat) {
            OrderInterfaceImpl.ProductObj productObj = (OrderInterfaceImpl.ProductObj) o;
            createTimes.add(Long.parseLong(productObj.getCreateTime()));
        }
        
        // 一次性查询所有产品信息
        List<Product> products = productServer.selectPricesByCreateTimes(createTimes);
        Map<Long, Product> productMap = new HashMap<>();
        for (Product product : products) {
            productMap.put(product.getCreateTime(), product);
        }
        
        // 构建统计信息
        for (Object o : productStat) {
            Map<String, Object> stat = new HashMap<>();
            OrderInterfaceImpl.ProductObj productObj = (OrderInterfaceImpl.ProductObj) o;
            long createTime = Long.parseLong(productObj.getCreateTime());
            Product product = productMap.get(createTime);
            
            if (product != null) {
                stat.put("name", product.getName());
                stat.put("amount", product.getPrice() * productObj.getSales());
                stat.put("sales", productObj.getSales());
                stat.put("createTime", productObj.getCreateTime());
                stat.put("price", product.getPrice());
                stats.add(stat);
            }
        }
        Date date2 = new Date();
        System.out.println(date2.getTime() - date1.getTime()+"msX");
        return stats;
    }
}